package Class::Scaffold::Factory;

use warnings;
use strict;
use Error;   # to get $Error::Depth;
use Error::Hierarchy::Util qw/assert_defined load_class/;


our $VERSION = '0.04';


use base 'Class::Scaffold::Storable';


sub notify_lookup_failure {
    my ($self, $handler_type, $spec) = @_;
    local $Error::Depth = $Error::Depth + 1;
    throw Class::Scaffold::Exception::NoSuchFactoryHandler(
        handler_type => $handler_type,
        spec         => join(', ', @$spec),
    );
}


sub get_class_name_for_handler {
    my ($self, $handler_type, $spec) = @_;

    assert_defined $handler_type, 'called without handler_type.';

    my $class = $self->every_hash($handler_type);
    for my $spec_el (@$spec) {

        # Stringify potential value object as using it as a hash key doesn't
        # trigger stringification automatically

        if (exists $class->{"$spec_el"}) {
            $class = $class->{"$spec_el"}
        } elsif (exists $class->{_AUTO}) {
            $class = $class->{_AUTO};
            # ignore the rest of the spec
            last;
        } else {
            $self->notify_lookup_failure($handler_type, $spec);
            return;    # undef to signal failure
        }
    }

    $class;
}


sub gen_handler {
    my ($self, $handler_type, $spec, %args) = @_;
    my $class = $self->get_class_name_for_handler($handler_type, $spec);
    load_class $class, $self->delegate->test_mode;
    $class->new(
        storage_type => $self->storage_type,
        %args
    );
}


1;


__END__

{% USE p = PodGenerated %}

=head1 NAME

{% p.package %} - large-scale OOP application support

=head1 SYNOPSIS

    {% p.package %}->new;

=head1 DESCRIPTION

=head1 METHODS

=over 4

{% p.write_methods %}

=back

{% p.write_inheritance %}

{% PROCESS standard_pod %}

=cut

